package com.heima.common.qiniu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.common.qiniu.util.UploadUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 谢金成
 * @date 2024/4/10 19:21
 */
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "qiniu")
public class ImageCensor {

    private String accessKeyId;
    private String secret;
    private List<String> scenes;

    public Map greenImageCensor(List<byte[]> imageList) throws Exception {
        Auth auth = Auth.create(accessKeyId, secret);

        String url = "http://ai.qiniuapi.com/v3/image/censor";
        String host = "ai.qiniuapi.com";
        String contentType = "application/json";
        String method = "POST";

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("suggestion", "pass");
        List<String> labels = new ArrayList<>();

        for (byte[] bytes :
                imageList) {
            String imgUrl = UploadUtil.upload(bytes, accessKeyId, secret);
            if (imgUrl != null) {
                Map<String, Object> body = new HashMap<>();
                Map<String, Object> data = new HashMap<>();
                Map<String, Object> params = new HashMap<>();
                data.put("uri", imgUrl);
                params.put("scenes", scenes);
                body.put("data", data);
                body.put("params", params);

                String bodyStr = JSONObject.toJSONString(body);

                String qiniuToken = "Qiniu " + auth.signQiniuAuthorization(url, method, bodyStr.getBytes(), contentType);

                StringMap header = new StringMap();
                header.put("Host", host);
                header.put("Authorization", qiniuToken);
                header.put("Content-Type", contentType);
                Configuration c = new Configuration(Region.huabei());
                Client client = new Client(c);
                Response response = null;
                try {
                    response = client.post(url, bodyStr.getBytes(), header, contentType);
                } catch (QiniuException e) {
                    e.printStackTrace();
                }

                if (response != null) {
                    Map map = JSON.parseObject(response.bodyString(), Map.class);
                    if (map.get("code").equals(200)) {
                        Map result = (Map) map.get("result");
                        Map scenes = (Map) result.get("scenes");

                        // 分场景
                        scenes.forEach((k, v) -> {
                            Map v1 = (Map) v;
                            if (!v1.get("suggestion").equals("pass")) {
                                resultMap.put("suggestion", (String) v1.get("suggestion"));
                                List details = (List) (v1.get("details"));
                                List label = (List) details.stream().map(d -> ((Map) d).get("label")).collect(Collectors.toList());
                                label.forEach(l -> {
                                    if (!labels.contains(l)) {
                                        labels.add((String) l);
                                    }
                                });
                            }
                        });
                    } else {
                        System.out.println("单张图片处理失败");
                        return null;
                    }
                } else {
                    System.out.println("单张图片处理失败");
                    return null;
                }
            } else {
                System.out.println("图片上传失败");
                return null;
            }
        }

        resultMap.put("labels", labels);
        return resultMap;
    }
}
